package com.yuexiao.config;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.yuexiao.entity.ResultInfo;
import com.yuexiao.pojo.Employee;
import com.yuexiao.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录成功时调用
 */
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Reference
    private EmployeeService employeeService;
    @Autowired
    private RedisUtil redisUtil;


    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {


        //获取当前登录用户
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        String name = "";

        if (principal instanceof UserDetails) {

            name = ((UserDetails) principal).getUsername();

        }

        if (principal instanceof Principal) {

            name = ((Principal) principal).getName();

        }

        //从数据库中再次查询用户信息放入session
        Employee employeeByUsername = employeeService.getEmployeeByUsername(name);
        if (employeeByUsername != null && employeeByUsername.getId() != null) {
            //放入session
            httpServletRequest.getSession().setAttribute("userInfo",employeeByUsername);
            //放入redis
            redisUtil.set("loginId",employeeByUsername.getId());
        }

        httpServletResponse.setContentType("application/json;charset=utf-8");
        httpServletResponse.setStatus(200);
        httpServletResponse.getWriter().write(JSON.toJSONString(ResultInfo.success(employeeByUsername)));
    }
}